<template>
  <div class="baccarat scrollBar">
    <div class="baccaratBox">
      <div class="newLotteryW">
        <div class="baccaratBetBox relative">
          <router-link :to="{name:'theResults',query:{code:$route.query.code,name:lotteryName}}" class="currentResult"
                       tag="div">
            <h3>第{{numberLot}}期开奖结果：</h3>
            <div class="resultBox clearFiex">
              <p class="left floatLeft">
                <img :src="bankerIcon" alt="">
                <img :src="_Modulation.getSmallCard(curResCardType[resIndex],resItem?resItem:'?')" alt=""
                     v-for="(resItem,resIndex) in curResData"
                     v-if="resIndex<2">
              </p>
              <p class="right floatRight">
                <img :src="_Modulation.getSmallCard(curResCardType[resIndex],resItem?resItem:'?')" alt=""
                     v-for="(resItem,resIndex) in curResData"
                     v-if="resIndex>1">
                <img :src="idleIcon" alt="">
              </p>
            </div>
          </router-link>
          <div>
          
          </div>
          <router-link :to="{name:'colorRules',query:{code:$route.query.code}}" tag="div" class="rulesBox">游戏规则
          </router-link>
          <div class="lotteryBetBox ">
            <div class="cutDownTimeBox">
              <p v-if="!stopBet">{{nextnumberLot}}期 倒计时</p>
              <p v-if="stopBet">封盘倒计时</p>
              <p>
                <span>{{countDownStr.charAt(0)}}</span>
                <span>{{countDownStr.charAt(1)}}</span>
                <span>:</span>
                <span>{{countDownStr.charAt(3)}}</span>
                <span>{{countDownStr.charAt(4)}}</span>
                <span>:</span>
                <span>{{countDownStr.charAt(6)}}</span>
                <span>{{countDownStr.charAt(7)}}</span>
              </p>
            </div>
            <ul class="betArea relative">
              <li class="resultCard relative" v-for="(resCardItem,ind) in curResData">
                <img :class="{flip:true, in:!isOpen,out:isOpen}" :src="cardFire[ind]" alt="">
                <img :class="{flip:true, out:!isOpen,in:isOpen}" :src="_Modulation.getBigCard(curResCardType[ind],resCardItem)"
                     alt="" v-if="resCardItem">
              </li>
              <li :class="{left:betNumItem.id==4143,middleL:betNumItem.id==4144,middle:betNumItem.id==4145,middleR:betNumItem.id==4146,right:betNumItem.id==4147,onSel:betNumItem.status}"
                  class="betNumListItem" v-for="(betNumItem,index) in betNumData"
                  @click="numerical($event, betNumItem, index)" @contextmenu="colorMouseDown($event,betNumItem,index)">
                <img :src="_Modulation.getTextImg(betNumItem.id)" alt="">
                <p class="odds">{{betNumItem.odds}}</p>
                <div class="chip" :class="{chipHidden:!betNumItem.status}">
                  <img src="" alt="">
                </div>
              </li>
            </ul>
          </div>
        </div>
        <div class="confirmBetBox">
          <div class="chipsBox">
            <div class="chipM relative">
              <div class="chipItem" :class="{chipOn:chipIndex==chipCurIndex}" v-for="(chipItem,chipIndex) in chipVal"
                   @click="chipSelectEvent(chipIndex,chipItem)"><img :src="_Modulation.getChipImg(chipItem)" alt="">
              </div>
              <div class="chipLBox">
                <div class="chipL"><p>桌面金额：{{totalMoney}}元</p></div>
              </div>
              <div class="chipRBox">
                <div class="chipR"><p>账户金额：{{accountMoney}}元</p></div>
                <div class="chipItem" :class="{chipOn:isAllIn}"><img :src="_Modulation.getChipImg('allIn')" alt="">
                </div>
              </div>
            </div>
          </div>
          <div class="functionBtn">
            <div class="funcBtnItem" @click="empty"></div>
            <div class="funcBtnItem" @click="athecticSet"></div>
            <div class="funcBtnItem" :class="{on:isAllIn}" @click="allInEvent"></div>
          </div>
        </div>
        <newBetRecord ref="betRecord"></newBetRecord>
      </div>
    </div>
    <!--封盘音效-->
    <audio :src="indexPlate" class="indexAudio"></audio>
    <!--最新开奖结果音效-->
    <audio :src="indexOpenLottery" class="indexlotteryWav"></audio>
    <setABet v-if="setABetTrue"></setABet>
  </div>
</template>

<script>
  import './main.scss';
  import {mapState} from 'vuex';
  import setABet from '../../theColor/color/transfer/setABet/index';
  import newBetRecord from '../newBetRecord/index';
  
  export default {
    data() {
      return {
        lotteryName: '', //彩种名称
        playGroupName: '',//玩法组名
        setABetTrue: false,
        isOpen: false,//是否开奖
        stopBet: false,//是否封盘
        countDownStr: '00:00:00', //倒计时值
        countDownSecond: '',//倒计时
        stopBetCountDownSecond: '',//封盘倒计时
        whetherToSeal: false, //是否封盘
        isAllIn: false, //是否梭哈
        lotTimeNumber: 0,
        stopBet: false,
        interValObj: '',//是否关闭倒计时
        indexPlate: require('../../../assets/audio/plate.wav'), //封盘音乐
        indexOpenLottery: require('../../../assets/audio/lottery.wav'), //开奖音乐
        bankerIcon: require('../../../assets/images/theColor/baccarat/icon/banker.png'),
        idleIcon: require('../../../assets/images/theColor/baccarat/icon/idle.png'),
        cardFire: [
          require('../../../assets/images/theColor/baccarat/bet/card-blue.gif'),
          require('../../../assets/images/theColor/baccarat/bet/card-blue.gif'),
          require('../../../assets/images/theColor/baccarat/bet/card-red.gif'),
          require('../../../assets/images/theColor/baccarat/bet/card-red.gif'),
        ],
        chipVal: [1, 5, 10, 50, 100, 1000, 10000],
        chipCurIndex: 2,//选中筹码下标
        currentChip: 10,//默认选中筹码
        nextnumberLot: '',//当前投注期号
        numberLot: '',//上一期期号
        numberLotCopy: '0',//上一期期号
        setTimer: null,
        curResData: ['', '', '', ''],//当前开奖结果
        curResCardType: ['1', '2', '3', '4'],//开奖结果牌的花色
        hisRewordData: [],//开奖历史数据
        betNumData: [],//投注号码数据
        isStopSale: false,//是否停售
        BettingData: [],//订单数据
        playData: [],//玩法数据
        totalMoney: 0,//投注总额
        accountMoney: 0,//账户余额
        accountMoneyCopy: 0,//账户余额
      }
    },
    computed: {
      ...mapState({
        recordColorData: state => state.mutations.recordColorData,
        userInfo: state => state.mutations.userInformation,
        bottomPourData: state => state.mutations.bottomPourData,
      }),
    },
    activated() {
      this.init();
      this.activation();
    },
    deactivated() {
      let that = this;
      window.clearInterval(that.interValObj);
      window.clearInterval(that.setTimer);
      this.empty();
      that.isStopSale = false;
    },
    methods: {
      init() {
        this.clearData();
        this.initData();
        this.getlotteryInfo();
      },
      initData() {
        this.$refs.betRecord.getMyBetRecData();
        let that = this,
          index = parseInt(that.$route.query.code);
        let data = that.recordColorData[index].data;
        if (that.recordColorData[index].data.length <= 0) return;
        that.isStopSale = data.status == '1' ? false : true;
        if (!data.code) return;
        that.nextnumberLot = data.nowNumber || '';
        that.lotteryName = data.name || '';
        that.numberLot = data.number || '';
        that.playGroupName = data.groupList[0].name || '';
        that.accountMoneyCopy = that.userInfo.memberInfo.amount;
//        that.betNumData = data.groupList[0].dataList||[];
        that.empty();
      },
      clearData() {
        this.chipCurIndex = 2;
        this.currentChip = 10;
        
        this.curRecTitIndex = 0;
        this.setABetTrue = false;
        
        this.nextnumberLot = '';
        this.numberLot = '';
      },
      //监听浏览器当前页面是否被激活的事件
      activation() {
        let that = this;
        let reLoadLeftTime = false;
        //监听浏览器当前页面是否被激活的事件
        let hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' : null;
        let visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
        let onVisibilityChange = function () {
          if (!document[hiddenProperty]) {
            reLoadLeftTime = true;
            window.cancelAnimFrame = (function () {
              return window.cancelAnimationFrame ||
                window.webkitCancelAnimationFrame ||
                window.mozCancelAnimationFrame ||
                function (id) {
                  clearTimeout(id);
                };
            })();
            that.getlotteryInfo();
          }
        };
        document.addEventListener(visibilityChangeEvent, onVisibilityChange);
        
        that.$router.beforeEach((route, redirect, next) => {
          document.removeEventListener(visibilityChangeEvent, onVisibilityChange);
          next();
        });
      },
      //获取彩种数据
      getlotteryInfo() {
        let that = this,
          lotteryId = that.$route.query.code,
          lotteryTrue = that.$route.query.lotteryTrue;
        if (!lotteryId) return;
        if (lotteryTrue) {
          that._Util.post(that, that._Api.POST_CREDIT_LOTTERY_DATA, {lotteryCode: lotteryId}, (data) => {
            that.playData = data;
            that.curResData = data.data || '';
            that.curResCardType = data.wave ? data.wave.split(',') : ['1', '2', '3', '4'];
            that.isStopSale = data.status == '1' ? false : true;
            that.numberLot = data.number || '';
//            if(that.numberLot>that.numberLotCopy){
//              that.numberLotCopy = data.number || '0';
//            }
            that.lotteryName = data.name || '';
            that.accountMoney = data.amount || '0';
            that.accountMoneyCopy = data.amount || '0';
            //获取开奖历史数据
            that.hisRewordData = data.dataLit || [];
            that.hisRewordData.forEach((v) => {
              v.wave = v.wave ? v.wave.split(',') : ['1', '2', '3', '4'];
            });
            that.$store.commit('HIS_REW_DATA', that.hisRewordData);
            if (data.amount && that.userInfo) {
              that.userInfo.memberInfo.amount = data.amount;
            }
            if (!that.isStopSale) {
              that.nextnumberLot = data.nowNumber || '';
              that.upDateLastData();
            }
            //倒计时数据
            that.countDownSecond = data.countDown || -1;
            that.stopBetCountDownSecond = data.stopCountDown;
            that.startCountDown();
            //投注区数据
            let betData = data.groupList || [];
            if (betData.length > 0 && betData[0].playList.length > 0) {
              that.betNumData = betData[0].playList[0].dataList || [];
              that.playGroupName = betData[0].name || '';
              that.betNumData.forEach((v) => {
                v.amount = 0;
                v.status = false;
              });
            }
            let lotteryData = {
              id: parseInt(that.$route.query.code),
              data: data
            };
            that.$store.commit('RECORD_COLOR_DATA', lotteryData);
          });
        }
      },
      // 更新新的一期开奖结果
      upDateLastData() {
        let that = this;
        that.setTimer = setInterval(() => {
          if (parseInt(that.nextnumberLot) - parseInt(that.numberLot) === 1 || !that.$route.query.code) {
            clearInterval(that.setTimer);
          } else {
            let submitData = {
              lotteryCode: that.$route.query.code
            };
            if (!that.isStopSale) {
              that._Util.post(that, that._Api.POST_LOTTERY_DATA_LAST, submitData, (data) => {
                // 更新开奖号码
                that.numberLot = data.openDataList[0].number || '';
                that.nextnumberLot = data.nextNumber || '';
                that.curResData = data.openDataList[0].data || [];
                that.curResCardType = data.openDataList[0].wave ? data.openDataList[0].wave.split(',') : ['1', '2', '3', '4'];
                //获取开奖历史数
                if (that.numberLot > that.hisRewordData[0].number) {
                  data.openDataList[0].wave = data.openDataList[0].wave ? data.openDataList[0].wave.split(',') : ['1', '2', '3', '4'];
                  that.hisRewordData.unshift(data.openDataList[0]);
                  that.hisRewordData = that.hisRewordData.slice(0, 10);
                  that.$store.commit('HIS_REW_DATA', that.hisRewordData);
                }
              }, (data) => {
                clearInterval(that.setTimer);
              }, '', true);
            } else {
              clearInterval(that.setTimer);
            }
          }
        }, 3000);
      },
      // 选号触发
      numerical(e, baccard, index) {
        let that = this;
        if (that.accountMoney <= 0) {
          that._Util.showAlert('余额不足');
          return;
        }
        if (that.accountMoney < that.currentChip) {
          that._Util.showAlert('余额不足');
          return;
        }
        if (!baccard.status) {
          baccard.status = true;
        }
        baccard.amount += parseFloat(that.currentChip);
//        that.totalAmount += parseFloat(selectChip);
        // 金币效果
        let chipAmount = $(".betNumListItem").eq(index);
        setTimeout(() => {
          that._Util.parabola(e, baccard, chipAmount);
        }, 50);
        that.retentionInputData(baccard);
      },
      //鼠标右键事件
      colorMouseDown(e, baccard, index) {
        let that = this;
        baccard.status = false;
        if (e.which == 3) {
          baccard.amount = 0;
          var amount = baccard.amount;
//          $(clsObj).eq(index).find('.credAmountDiv').eq(index).removeClass('credAmountAnimation').text(amount);
          that.retentionInputData(baccard);
          e.preventDefault();
        }
      },
      //确定投注
      athecticSet() {
        let that = this;
        if (that.isStopSale) {
          that._Util.showAlert('暂停销售');
          return;
        }
        if (that.whetherToSeal) {
          that._Util.showAlert('已封盘');
          return;
        }
        if (that.BettingData.length > 0) {
          let athectData = {
            number: that.nextnumberLot,
            name: that.lotteryName,
            data: that.BettingData
          };
          that.$store.commit('INIT_LOTTERY_DATA', athectData);
          that.setABetTrue = true;
        } else {
          that._Util.showAlert('你还没有投注记录');
        }
      },
      // 保留投注数据
      retentionInputData(list) {
        let that = this;
        let injectionData = {
          playedGroupCode: that.playData.groupList[0].code || '',                              //玩法组code
          playedGroupName: that.playGroupName,//玩法组名称
          playedId: list.id,//玩法id
          playedName: list.name,//玩法名称
          actionNum: 1,//单个玩法注数
          actionData: list.name,//投注号码
          rebate: 0,//返点
          rebateAmount: 0,
          amount: list.amount,//金额
          odds: list.odds,    //赔率
          mode: 2,            //模式   1.官方   2信用
          multiple: 1
        };
        that.addInputData(injectionData);
      },
      // 添加投注数据
      addInputData(json) {
        let that = this;
        let len = that.BettingData.length;
        if (that.BettingData.length === 0) {
          if (json.amount > '0') {
            that.BettingData.push(json);
          }
        } else {
          that.BettingData.forEach((bet, i) => {
            bet.playedId = parseInt(bet.playedId);
            json.playedId = parseInt(json.playedId);
            if (bet.playedId === json.playedId) {
              if (json.amount > '0') {
                that.BettingData.splice(i, 1);
                that.BettingData.push(json);
              } else {
                that.BettingData.splice(i, 1);
              }
              return;
            } else if (i === len - 1) {
              if (json.amount > '0') {
                that.BettingData.push(json);
              } else {
                that.BettingData.splice(i, 1);
              }
              
            }
          });
        }
        that.totalCalVal();
      },
      //计算总额
      totalCalVal() {
        let that = this,
          amountObj = that._Util.totalNumberNotes(that.BettingData);
        that.totalMoney = amountObj.amount;
        that.accountMoney = parseInt((that.accountMoneyCopy - that.totalMoney) * 100) / 100;
      },
      //倒计时方法
      startCountDown() {
        let that = this;
        that.$store.state.mutations.bottomPourData = false;
        that.stopBet = false;
        window.clearInterval(that.interValObj);
        if (that.countDownSecond > 0 && !that.isStopSale) {
          that.interValObj = window.setInterval(
            function () {
              if (that.$route.query.lotteryTrue) {
                that.countDown();
              }
            }.bind(this), 1000);
        }
      },
      countDown() {
        let that = this;
        //倒计时
        if (that.countDownSecond > 0) {
          that.lotTimeNumber = 0;
          that.countDownSecond = that.countDownSecond - 1;
          if (that.stopBetCountDownSecond > 0) {
            that.stopBetCountDownSecond -= 1;
          } else {
            if (that.stopBetCountDownSecond === 0) {
              that._Util.showAlert('已封盘');
              that.plateOpen();
              that.$store.state.mutations.bottomPourData = true;
            }
            that.stopBetCountDownSecond -= 1;
            that.stopBet = true;
          }
          that.countDownStr = that._Util.formatTime(that.stopBetCountDownSecond, that.countDownSecond, that.stopBet);
        } else if (that.countDownSecond === 0) {
          //回调方法
          if (that.lotTimeNumber === 0) {
            that._Util.showAlert('新的一期已经开始');
          } else if (that.lotTimeNumber === 3) {
            that._Util.showAlert('刷新页面重试');
            return;
          }
//          that.$parent.setABetTrue = false;
          that.stopBet = false;
          // that.headerInitData();
          that.getlotteryInfo();
          that.empty();
          that.lotTimeNumber += 1;
        }
      },
      // 清空
      empty() {
        let that = this;
        // 清空状态
        that.betNumData.forEach((v) => {
          v.status = false;
          v.amount = 0;
        });
        that.betNumData = that.betNumData;
        // 清空总金额
        that.totalMoney = 0;
        that.accountMoney = that.accountMoneyCopy;
        that.isAllIn = false;
        this.chipCurIndex = 2;
        this.currentChip = 10;
        // 清空保存数据
        that.BettingData = [];
      },
      //封盘音效
      plateOpen() {
        let indexAudio = document.getElementsByClassName('indexAudio')[0];
        indexAudio.play();
      },
      //筹码选中事件
      chipSelectEvent(index, val) {
        this.chipCurIndex = index;
        this.currentChip = val;
        this.isAllIn = false;
      },
      //梭哈点击事件
      allInEvent() {
        this.chipCurIndex = 7;
        this.isAllIn = true;
        this.currentChip = this.accountMoney;
      },
    },
    components: {
      setABet,
      newBetRecord,
    },
    watch: {
      'bottomPourData'() {
        if (this.bottomPourData) {
          this.whetherToSeal = true;
        } else {
          this.whetherToSeal = false;
        }
      },
      'curResData'() {
        let that = this;
        if (this.curResData.length > 0 && this.numberLot - this.numberLotCopy > 0) {
          this.isOpen = true;
          this.numberLotCopy = this.numberLot;
          setTimeout(() => {
            that.isOpen = false;
          }, 6000);
        } else {
          this.isOpen = false;
        }
        
      },
    }
  }
</script>
